/***************************************************************************************
 The copyright in this software is being made available under the BSD License, included
 below. This software may be subject to other third party rights,including patent rights,
 and no such rights are granted under this license.

 Regents of the Tsinghua University, Peking University, Zhejiang University, HKUST
 Tsinghua University, Peking University, Zhejiang University, HKUST 2011

 Copyright (c) 2011, Regents of the Tsinghua University, Peking University, Zhejiang
 University, HKUST. All Rights Reserved.

 Redistribution and use in source and binary forms, with or without modification, are
 permitted provided that the following conditions are met:
   * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   * Neither the names of the copyright holders nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 OF SUCH DAMAGE.
***************************************************************************************/

/**************************************************************************************
* File name: header.c
* Function: Slice headers
*
*************************************************************************************
*/

#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

#include "contributors.h"
#include "memalloc.h"
#include "global.h"
#include "defines.h"
#include "vlc.h"
#include "header.h"
camera_para_t CameraParameter, *camera = &CameraParameter;

const int InterlaceSetting[] = { 4, 4, 0, 5, 0, 5, 0, 5, 3, 3, 3, 3, 0,
                                 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 4, 0
                               };

/*
*************************************************************************
* Function:sequence header
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

void sequence_header( char *buf, int startcodepos, int length )
{

    memcpy( currStream->stream_buffer, buf, length );

    currStream->code_len = currStream->bitstream_length = length;

    currStream->read_len = currStream->frame_bitoffset = ( startcodepos + 1 ) * 8;

    profile_id = u_v( 8, "profile_id" );

    level_id = u_v( 8, "level_id" );

    if ( profile_id == 0x20 )
        num_b_picture = u_v( 3,"numberBidirectionallyPredictedPictures" ); //xy_110703

    //progressive_sequence = u_v(1, "progressive_sequence");

    horizontal_size = u_v( 14, "horizontal_size" );

    vertical_size = u_v( 14, "vertical_size" );

    frame_rate_code = u_v( 4, "frame_rate_code" );

    bit_rate_lower = u_v( 18, "bit_rate_lower" );

    u_v( 1, "marker bit" );

    bit_rate_upper = u_v( 12, "bit_rate_upper" );

    chroma_format = u_v( 2, "chroma_format" );

    sample_precision = u_v( 2, "sample_precision" );

    aspect_ratio_information = u_v( 4, "aspect_ratio_information" );

    u_v( 2, "marker bit" );

    pictureApplicationDataEnable =  u_v( 1, "pictureApplicationDataEnable" );

    u_v( 5, "reseved bits" );

    img->succe_b = num_b_picture; //xy_110703
    img->b_num = img->succe_b;

    img->width = horizontal_size;

    img->height = vertical_size;

    img->width_cr = ( img->width >> 1 );

    if ( chroma_format == 2 )

        img->height_cr = ( img->height );
    else

        img->height_cr = ( img->height >> 1 );

    img->PicWidthInMbs = img->width / MB_BLOCK_SIZE;

    img->PicHeightInMbs = img->height / MB_BLOCK_SIZE;

    img->PicSizeInMbs = img->PicWidthInMbs * img->PicHeightInMbs;

    img->buf_cycle = input->buf_cycle + 1;

    img->max_mb_nr = ( img->width * img->height ) / ( MB_BLOCK_SIZE * MB_BLOCK_SIZE );

    IsStuffingPattern( 0, currStream->bitstream_length * 8 - currStream->frame_bitoffset );     //rm52k
}


void video_edit_code_data( char *buf, int startcodepos, int length )
{

    currStream->frame_bitoffset = currStream->read_len = ( startcodepos + 1 ) * 8;

    currStream->code_len = currStream->bitstream_length = length;

    memcpy( currStream->stream_buffer, buf, length );

    vec_flag = 1;

}

//added by xy_110703
/*
*************************************************************************
* Function:picture header
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

void pic_header( char *buf, int startcodepos, int length )
{

    currStream->frame_bitoffset = currStream->read_len = ( startcodepos + 1 ) * 8;

    currStream->code_len = currStream->bitstream_length = length;

    memcpy( currStream->stream_buffer, buf, length );

    //bbv_delay = u_v(16, "bbv delay");

    if ( pictureApplicationDataEnable )
    {
        time_code = u_v( 18, "time_code" );
        marker_bit = u_v( 1, "marker_bit" );
        time_code = u_v( 18, "time_code" );
        marker_bit = u_v( 1, "marker_bit" );
        time_code = u_v( 2, "time_code" );

    }

    fixed_picture_qp = u_v( 1, "fixed_picture_qp" );

    picture_qp = u_v( 6, "picture_qp" );

    vbs_enable = u_v( 1,"vbs_enable" );
#ifdef OPT_HP
	img->tag_hp = u_v( 2, "hierarchical p coding");
#endif
    img->qp = picture_qp;

    //img->vbs_qp_16x16 = vbs_qp_16x16;
    //img->vbs_qp_4x4 = vbs_qp_4x4;

    img->pic_distance = picture_distance;

    //img->type = I_IMG; //xy_110703
    img->type = img->next_frame_type;

#if SYNTAX_REPORT
    fprintf( p_sreport, "\n*********** Pic: %d (I/P) Type %s **********\n", picture_distance, "INTRA" );
#endif

    IsStuffingPattern( 0, currStream->bitstream_length * 8 - currStream->frame_bitoffset );

}



/*
*************************************************************************
* Function:decode extension and user data
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

void extension_data( char *buf, int startcodepos, int length )
{

    int ext_ID;

    memcpy( currStream->stream_buffer, buf, length );

    currStream->code_len = currStream->bitstream_length = length;

    currStream->read_len = currStream->frame_bitoffset = ( startcodepos + 1 ) * 8;

    ext_ID = u_v( 4, "extension ID" );

    switch ( ext_ID )

    {

        case SEQUENCE_DISPLAY_EXTENSION_ID:

            sequence_display_extension();

            break;

        case COPYRIGHT_EXTENSION_ID:

            copyright_extension();

            break;

        case PICTURE_DISPLAY_EXTENSION_ID:

            picture_display_extension();

            break;
        case CAMERAPARAMETERS_EXTENSION_ID:

            cameraparameters_extension();

            break;

        default:

            printf( "reserved extension start code ID %d\n", ext_ID );

            break;

    }

}

/*
*************************************************************************
* Function: decode sequence display extension
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void sequence_display_extension()
{

    video_format = u_v( 3, "video format ID" );

    video_range = u_v( 1, "video range" );

    color_description = u_v( 1, "color description" );

    if ( color_description )

    {

        color_primaries = u_v( 8, "color primaries" );

        transfer_characteristics = u_v( 8, "transfer characteristics" );

        matrix_coefficients = u_v( 8, "matrix coefficients" );

    }

    display_horizontal_size = u_v( 14, "display_horizontaol_size" );

    u_v( 1, "marker bit" );

    display_vertical_size = u_v( 14, "display_vertical_size" );

    u_v( 2, "reserved bits" );

    IsStuffingPattern( 0, currStream->bitstream_length * 8 - currStream->frame_bitoffset );     //rm52k
}


/*
*************************************************************************
* Function: decode picture display extension
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void picture_display_extension()
{

    int NumberOfFrameCentreOffsets;

    int i;

    if ( /*progressive_sequence ==*/ 1 )
    {
        if ( repeat_first_field == 1 )
        {
            if ( top_field_first == 1 )
                NumberOfFrameCentreOffsets = 3;
            else
                NumberOfFrameCentreOffsets = 2;
        }
        else
        {
            NumberOfFrameCentreOffsets = 1;
        }

    }
    //else
    //{
    //
    //    if (img->picture_structure == 0)
    //    {
    //
    //      NumberOfFrameCentreOffsets = 1;
    //
    //    }
    //    else
    //    {
    //
    //      if (repeat_first_field == 1)
    //
    //        NumberOfFrameCentreOffsets = 3;
    //
    //      else
    //
    //        NumberOfFrameCentreOffsets = 2;
    //
    //    }
    //
    //}

    for ( i = 0; i < NumberOfFrameCentreOffsets; i++ )
    {

        frame_centre_horizontal_offset[i] = u_v( 16, "frame_centre_horizontal_offset" );

        u_v( 1, "marker_bit" );

        frame_centre_vertical_offset[i] = u_v( 16, "frame_centre_vertical_offset" );

        u_v( 1, "marker_bit" );

    }

    IsStuffingPattern( 0, currStream->bitstream_length * 8 - currStream->frame_bitoffset );
}


/*
*************************************************************************
* Function:user data //sw
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

void user_data( char *buf, int startcodepos, int length )
{
    //int user_data;
    //int i;
    memcpy( currStream->stream_buffer, buf, length );

    currStream->code_len = currStream->bitstream_length = length;

    currStream->read_len = currStream->frame_bitoffset = ( startcodepos + 1 ) * 8;

    //for (i = 0; i < length - 4; i++)
    // user_data = u_v(8, "user data");

}


/*
*************************************************************************
* Function:Copyright extension //sw
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

void copyright_extension()
{

    //int marker_bit;

    copyright_flag = u_v( 1, "copyright_flag" );

    copyright_identifier = u_v( 8, "copyright_identifier" );

    original_or_copy = u_v( 1, "original_or_copy" );

    /* reserved */
    reserved_data = u_v( 7, "reserved_data" );

    marker_bit = u_v( 1, "marker_bit" );

    copyright_number_1 = u_v( 20, "copyright_number_1" );

    marker_bit = u_v( 1, "marker_bit" );

    copyright_number_2 = u_v( 22, "copyright_number_2" );

    marker_bit = u_v( 1, "marker_bit" );

    copyright_number_3 = u_v( 22, "copyright_number_3" );

    IsStuffingPattern( 0, currStream->bitstream_length * 8 - currStream->frame_bitoffset );     //rm52k
}


/*
*************************************************************************
* Function:camera parameters extension //sw
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

void cameraparameters_extension()
{

    u_v( 1, "reserved" );

    u_v( 7, "camera id" );

    u_v( 1, "marker bit" );

    u_v( 22, "height_of_image_device" );

    u_v( 1, "marker bit" );

    u_v( 22, "focal_length" );

    u_v( 1, "marker bit" );

    u_v( 22, "f_number" );

    u_v( 1, "marker bit" );

    u_v( 22, "vertical_angle_of_view" );

    u_v( 1, "marker bit" );

    u_v( 16, "camera_position_x_upper" );

    u_v( 1, "marker bit" );

    u_v( 16, "camera_position_x_lower" );

    u_v( 1, "marker bit" );

    u_v( 16, "camera_position_y_upper" );

    u_v( 1, "marker bit" );

    u_v( 16, "camera_position_y_lower" );

    u_v( 1, "marker bit" );

    u_v( 16, "camera_position_z_upper" );

    u_v( 1, "marker bit" );

    u_v( 16, "camera_position_z_lower" );

    u_v( 1, "marker bit" );

    u_v( 22, "camera_direction_x" );

    u_v( 1, "marker bit" );

    u_v( 22, "camera_direction_y" );

    u_v( 1, "marker bit" );

    u_v( 22, "camera_direction_z" );

    u_v( 1, "marker bit" );

    u_v( 22, "image_plane_vertical_x" );

    u_v( 1, "marker bit" );

    u_v( 22, "image_plane_vertical_y" );

    u_v( 1, "marker bit" );

    u_v( 22, "image_plane_vertical_z" );
    u_v( 1, "marker bit" );

    u_v( 32, "reserved data" );

    IsStuffingPattern( 0, currStream->bitstream_length * 8 - currStream->frame_bitoffset );     //rm52k
}

/*
*************************************************************************
* Function:To calculate the poc values
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/

void calc_picture_distance( image_t *img )
{

    static int flag = 0;

    // for POC mode 0:
    unsigned int MaxPicDistanceLsb = ( 1 << 8 );

    flag++;

    // for POC mode 1:

    // Calculate the MSBs of current picture
    if ( img->pic_distance < img->PrevPicDistanceLsb &&
            ( img->PrevPicDistanceLsb - img->pic_distance ) >= ( MaxPicDistanceLsb / 2 ) )

        img->CurrPicDistanceMsb = img->PicDistanceMsb + MaxPicDistanceLsb;

    else if ( img->pic_distance > img->PrevPicDistanceLsb &&
              ( img->pic_distance - img->PrevPicDistanceLsb ) > ( MaxPicDistanceLsb / 2 ) )

        img->CurrPicDistanceMsb = img->PicDistanceMsb - MaxPicDistanceLsb;

    else

        img->CurrPicDistanceMsb = img->PicDistanceMsb;

    // 2nd
    img->toppoc = img->CurrPicDistanceMsb + img->pic_distance;

    img->bottompoc = img->toppoc + img->delta_pic_order_cnt_bottom;

    // last: some post-processing.
    if ( img->toppoc <= img->bottompoc )
        img->ThisPOC = img->framepoc = img->toppoc;
    else
        img->ThisPOC = img->framepoc = img->bottompoc;

    //frame pix  -  use toppoc/2
    img->tr_frm = img->ThisPOC / 2;
    img->tr = img->ThisPOC;
    img->tr_fld = img->ThisPOC;

    if ( img->type != B_IMG )
    {
        img->imgtr_last_prev_P = img->imgtr_last_P;
        img->imgtr_last_P = img->imgtr_next_P;

        img->imgtr_next_P = picture_distance;
        img->Bframe_number = 0;
    }

    if ( img->type == B_IMG )

    {

        img->Bframe_number++;

    }

}


/*
*************************************************************************
* Function:slice header
* Input:
* Output:
* Return:
* Attention:
///frame coding/////////
P    img->lum_scale[0]  fw[0]
img->lum_scale[1]  fw[1]
B      img->lum_scale[0]  fw[0]
img->lum_scale[1]  bw[0]
///field coding////////
P    img->lum_scale[0]  fw[0] ; img->lum_scale[1]  fw[1]
img->lum_scale[2]  fw[2] ; img->lum_scale[3]  fw[3]
B    img->lum_scale[0]  fw[0] ; img->lum_scale[1]  bw[0]
img->lum_scale[2]  fw[1] ; img->lum_scale[3]  bw[1]
*************************************************************************
*/

void slice_header( char *buf, int startcodepos, int length )
{
    int stuff_bits = 0;

    memcpy( currStream->stream_buffer, buf, length );

    currStream->code_len = currStream->bitstream_length = length;

    currStream->read_len = currStream->frame_bitoffset = ( startcodepos ) * 8;
    slice_vertical_position = u_v( 8, "slice vertical position" );

    if ( vertical_size > 2800 )
        slice_vertical_position_extension = u_v( 3, "slice vertical position extension" );

    if ( !fixed_picture_qp )
    {
        fixed_slice_qp = u_v( 1, "fixed_slice_qp" );

        slice_qp = u_v( 6, "slice_qp" );

        img->qp = slice_qp;
    }

    stuff_bits = 8 - ( currStream->frame_bitoffset%8 );
    u_v( stuff_bits, "Stuff bits for byte align" );
}


/*
*************************************************************************
* Function:Error handling procedure. Print error message to stderr and exit
with supplied code.
* Input:text
Error message
* Output:
* Return:
* Attention:
*************************************************************************
*/

void error( char *text, int code )
{

    fprintf( stderr, "%s\n", text );

    exit( code );

}



/*
*************************************************************************
* Function: Check the settings of progressive_sequence, progressive_frame,
picture_structure, top_field_first and repeat_first_field
* Input:    Index of the input parameters
* Output:
* Return:
* Attention:
* Author: Xiaozhen ZHENG, 200811, rm52k
*************************************************************************
*/
int check_interlace_setting( int idx )
{

    //0: OK
    //1: progressive_sequence
    //2: progressive_frame
    //3: picture_structure
    //4: top_field_first
    //5: repeat_first_field

    int status;

    status = InterlaceSetting[idx];

    switch ( status )
    {

        case 0:

            return 1;

        case 1:

            CSyntax = 0;

#if SYNTAX_REPORT
            fprintf( p_sreport, "Invalid setting of progressive_sequence!\n" );
#endif
            return 0;

        case 2:

            CSyntax = 0;
#if SYNTAX_REPORT
            fprintf( p_sreport, "Invalid setting of progressive_frame!\n" );
#endif
            return 0;

        case 3:

            CSyntax = 0;
#if SYNTAX_REPORT
            fprintf( p_sreport, "Invalid setting of picture_structure!\n" );
#endif
            return 0;

        case 4:

            CSyntax = 0;
#if SYNTAX_REPORT
            fprintf( p_sreport, "Invalid setting of top_field_first!\n" );
#endif
            return 0;

        case 5:

            CSyntax = 0;
#if SYNTAX_REPORT
            fprintf( p_sreport, "Invalid setting of repeat_first_field!\n" );
#endif
            return 0;

        default:

            printf( "Invalid input!\n" );

            return 0;

    }

    return 1;

}
